#ifndef CUBES_ROTATE_H
#define CUBES_ROTATE_H

float get_move_speed(int level)
{
    float ds, step;
    ds = Max_Move_Speed - Move_Speed;
    step = ds/(Levels_Count-1);
    return Move_Speed + step*(level-1);
}

int cube_wait(Cube_P cube)
{
    float A_rad; float B_rad;
    float speed;
            
    A_rad = degs_to_rads(cube->angle);
    B_rad = degs_to_rads(90 - cube->angle);
    speed = get_move_speed(cube->level);
    cube->dy = speed * cos(A_rad);
    cube->dx = speed * cos(B_rad);
            
    cube->ay = cube->dy / AccelK;
    cube->ax = cube->dx / AccelK;
    cube->state = State_Waiting;
    return 1;
}

int cube_make_waiting_atackers_move(Cube_P cube)
{
    int i;
    Cube_P atacker;
    int res;
    res = 0;
    for(i = 0; i < CC; ++i)
    {
        atacker = &cubes[i];
        if(!atacker->enabled)
            continue;
        if(atacker->state != State_Waiting) {
            continue;
        }
        if(atacker->ID == cube->ID)
            continue;
        if(!atacker->target)
            continue;
        if(atacker->target->ID == cube->ID)
        {
            atacker->state = State_Moving;
            res = 1; 
            cube->target = 0;
            cube->state = State_Target;  
        }
    }
    return res;
    
}

int cube_make_target_move(Cube_P cube)
{
    Cube_P target;
    target = cube->target;
    if(target->state != State_Waiting)
        return 0;
    target->state = State_Moving;
    target->target->state = State_Target;
    target->target = 0;
    cube->state = State_Search;
    cube->target = 0;
    return 1;
}

int cubes_rotate()
{
    int i;
    Cube_P cube;
    
    //float x; float y;
    
    for(i = 0; i < CC; ++i) 
    {
        cube = &cubes[i];
        if(!cube->enabled)
            continue;
        if(cube->state != State_Rotating) {
            continue;
        }
        if(cube->target->state == State_Moving) {
            cube->target = 0;
            cube->state = State_Search;
            continue;
        }
        cube->angle += cube->delta_angle;
        cube->angle = normalize_angle(cube->angle);
        cube->rotated += fabs(cube->delta_angle);
        if(cube->rotated >= cube->max_rotation) {
            cube->angle = cube->end_angle;
            if(cube_make_waiting_atackers_move(cube)) {
                continue;
            }
            if(cube_make_target_move(cube)) {
                continue;
            }
            cube_wait(cube);
        }
    }
    return 1;
}

#endif
